package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Pattern;
/**
 * 酷狗官方接口
 * **/
@Slf4j
public class Plugin_ECARD_P003 implements ChannelService {
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return ChannelResult.success("success");
    }

    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {
        try {
            String curTime = String.valueOf(System.currentTimeMillis());
            String user_type = "1";
            String AccountVal = String.valueOf(data.get("AccountVal"));
            if (Pattern.matches("^1[3456789]\\d{9}$", AccountVal) == true) {
                user_type = "2";
            }
            String[] products = String.valueOf(data.get("SUPProductId")).split(",");
            String SUPProductId = products[1];
            String productType = products[0];

            Map<String, String> dataParams = new HashMap<>();
            dataParams.put("main_key", apiConfig.getString("USERID"));
            dataParams.put("out_trade_no", String.valueOf(data.get("ChannelOrderCode")));
            dataParams.put("user", AccountVal);
            dataParams.put("user_type", user_type);
            dataParams.put("product_type", productType);
            dataParams.put("days", SUPProductId);
            dataParams.put("sign_type", "sha1");
            dataParams.put("timestamp", curTime);

            String Signature=generateMacSignature(apiConfig.getString("SecretKey"),getSignStr(dataParams));
            dataParams.put("sign",Signature.toUpperCase());

            String url=apiConfig.getString("SubmitURL");
            String res= HttpTool.sendPost(url,dataParams);
            JSONObject retobj = JSONObject.parseObject(res);
            String status = retobj.getString("status");
            String code = retobj.getString("error_code");
            if ("0".equals(code) && "1".equals(status)){
                return  ChannelResult.IN_PROCESS();
            }else {
                if("20001".equals(code) || "36207".equals(code))
                {
                    return ChannelResult.error(code);
                }
                else
                {
                    return ChannelResult.FAILED(code);
                }
            }


        } catch (Exception ex) {
            log.error("酷狗提单接口出错:", ex);
            return ChannelResult.error("酷狗提单接口出错");
        }

    }

    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {
        try {
            String curTime = String.valueOf(System.currentTimeMillis());


            Map<String, String> dataParams = new HashMap<>();
            dataParams.put("main_key", apiConfig.getString("USERID"));
            dataParams.put("out_trade_no", String.valueOf(data.get("ChannelOrderCode")));
            dataParams.put("sign_type", "sha1");
            dataParams.put("timestamp", curTime);

            String Signature=generateMacSignature(apiConfig.getString("SecretKey"),getSignStr(dataParams));
            dataParams.put("sign",Signature.toUpperCase());

            String url=apiConfig.getString("QueryURL");
            String res= HttpTool.sendPost(url,dataParams);
            JSONObject retobj = JSONObject.parseObject(res);
            String status = retobj.getString("status");
            String code = retobj.getString("error_code");
            if ("0".equals(code) && "1".equals(status)){
                JSONObject result=retobj.getJSONObject("data");
                String order_state=result.getString("status");
                if ("1".equals(order_state)){
                    return ChannelResult.success("充值成功");
                }else if ("-1".equals(order_state)){
                    return ChannelResult.FAILED();
                }else if ("0".equals(order_state)){
                    return ChannelResult.IN_PROCESS();
                }else {
                    return ChannelResult.error(code+order_state);
                }
            }else {
                return ChannelResult.error(code+status);
            }


        } catch (Exception ex) {
            log.error("酷狗查询接口出错:", ex);
            return ChannelResult.error("酷狗查询接口出错");
        }

    }

    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return ChannelResult.success("success");

    }

    public static String getSignStr(Map<String, String> map) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null && item.getKey() != "") {
                    String key = String.valueOf(item.getKey());
                    String val = String.valueOf(item.getValue());
                    if(sb.length()>0){
                        sb.append("&");
                    }
                    if (StringUtils.hasLength(val)) {
                        sb.append(key +"="+ val);
                    }
                }
            }
            result = sb.toString();
        } catch (Exception e) {
            log.error("获取签名明文出错：", e);
            return null;
        }
        return result;
    }

    public static String generateMacSignature(String secret, String data) {
        byte[] byteHMAC = null;
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKey secretKey = new SecretKeySpec(secret.getBytes("utf-8"),
                    "HmacSHA1");
            mac.init(secretKey);
            byteHMAC = mac.doFinal(data.getBytes("utf-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String result = byte2hex(byteHMAC);
        return result;
    }

    //二行制转字符串
    public static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }
}